package com.cby.operation.common.widget.richtext

import android.text.Spanned
import android.util.Log
import org.xml.sax.XMLReader

/**
 * html标签解析工具
 *
 * @author 徐智伟
 * @create 2020-03-27
 */
object HtmlTagHelper {
    const val TAG = "HtmlTagHelper"
    fun <T> getLast(text: Spanned, kind: Class<T>?): T? {
        val objs = text.getSpans(0, text.length, kind)
        return if (objs.size == 0) {
            null
        } else {
            objs[objs.size - 1]
        }
    }

    /**
     * 获取标签的属性值
     * @param xmlReader
     * @param attrName
     * @return
     */
    fun getAttribute(xmlReader: XMLReader, attrName: String): String? {
        return getAttribute(xmlReader, attrName, null)
    }

    fun getAttribute(xmlReader: XMLReader, attrName: String, defaultAttr: String?): String? {
        try {
            val elementField = xmlReader.javaClass.getDeclaredField("theNewElement")
            elementField.isAccessible = true
            val element = elementField[xmlReader]
            val attsField = element.javaClass.getDeclaredField("theAtts")
            attsField.isAccessible = true
            val atts = attsField[element]
            val dataField = atts.javaClass.getDeclaredField("data")
            dataField.isAccessible = true
            val data = dataField[atts] as Array<String>
            val lengthField = atts.javaClass.getDeclaredField("length")
            lengthField.isAccessible = true
            val len = lengthField[atts] as Int
            for (i in 0 until len) {
                if (attrName == data[i * 5 + 1]) {
                    return data[i * 5 + 4]
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "handleTag: ", e)
        }
        return defaultAttr
    }
}